package org.jeecg.modules.nurse_hospital.controller;

import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.PermissionData;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.util.UUIDGenerator;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.common.system.vo.SelectTreeModel;
import org.jeecg.modules.nurse_goods.entity.NurseGoods;
import org.jeecg.modules.nurse_goods.service.INurseGoodsService;
import org.jeecg.modules.nurse_goods_detail.entity.NurseGoodsDetail;
import org.jeecg.modules.nurse_goods_detail.service.INurseGoodsDetailService;
import org.jeecg.modules.nurse_hospital.entity.NurseHospital;
import org.jeecg.modules.nurse_hospital.service.INurseHospitalService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.nurse_nurses.entity.NurseNurses;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.apache.shiro.authz.annotation.RequiresPermissions;

/**
 * @Description: 护理医院
 * @Author: jeecg-boot
 * @Date: 2024-05-20
 * @Version: V1.0
 */
@Api(tags = "护理医院")
@RestController
@RequestMapping("/nurse_hospital/nurseHospital")
@Slf4j
public class NurseHospitalController extends JeecgController<NurseHospital, INurseHospitalService> {
    @Autowired
    private INurseHospitalService nurseHospitalService;

    @Autowired
    private INurseGoodsDetailService nurseGoodsDetailService;

    @Autowired
    private INurseGoodsService nurseGoodsService;

    @Autowired
    private ISysUserService sysUserService;

    /**
     * 通过地区查询
     *
     * @param area
     * @return
     */
    @ApiOperation(value = "护理医院-通过地区查询", notes = "护理医院-通过地区查询")
    @GetMapping(value = "/queryByArea")
    public Result<?> queryByArea(@RequestParam(name = "area", required = true) String area) {
        List<NurseHospital> nurseHospitals = nurseHospitalService.list(new QueryWrapper<NurseHospital>().eq("area", area));
//        if (nurseHospitals.size() <= 0 ) {
//            return Result.error("未找到对应数据");
//        }
        return Result.OK(nurseHospitals);
    }

    /**
     * 分页列表查询
     *
     * @param nurseHospital
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "护理医院-分页列表查询")
    @ApiOperation(value = "护理医院-分页列表查询", notes = "护理医院-分页列表查询")
    @GetMapping(value = "/rootList")
    @PermissionData(pageComponent="nurse/nurse_hospital/NurseHospitalList")
    public Result<IPage<NurseHospital>> queryPageList(NurseHospital nurseHospital, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
        String hasQuery = req.getParameter("hasQuery");
        if (hasQuery != null && "true".equals(hasQuery)) {
            QueryWrapper<NurseHospital> queryWrapper = QueryGenerator.initQueryWrapper(nurseHospital, req.getParameterMap());
            List<NurseHospital> list = nurseHospitalService.queryTreeListNoPage(queryWrapper);
            IPage<NurseHospital> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } else {
            String parentId = nurseHospital.getPid();
            if (oConvertUtils.isEmpty(parentId)) {
                parentId = "0";
            }
            nurseHospital.setPid(null);
            String name = nurseHospital.getName();
            if (oConvertUtils.isEmpty(name)) {
                name = "%";
            }
            name=name.replaceAll("\\*", "");
            nurseHospital.setName(null);
            QueryWrapper<NurseHospital> queryWrapper = QueryGenerator.initQueryWrapper(nurseHospital, req.getParameterMap());
            // 使用 eq 防止模糊查询
            queryWrapper.eq("pid", parentId);
            queryWrapper.like("name", name);
            Page<NurseHospital> page = new Page<NurseHospital>(pageNo, pageSize);
            IPage<NurseHospital> pageList = nurseHospitalService.page(page, queryWrapper);
            return Result.OK(pageList);
        }
    }

    /**
     * 分页列表查询
     *
     * @param nurseHospital
     * @param pageNo
     * @param pageSize
     * @param req
     * @return
     */
    //@AutoLog(value = "护理医院-分页列表查询")
    @ApiOperation(value = "护理医院-分页列表查询", notes = "护理医院-分页列表查询")
    @GetMapping(value = "/rootListAll")
    public Result<IPage<NurseHospital>> queryPageListAll(NurseHospital nurseHospital, @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo, @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize, HttpServletRequest req) {
            QueryWrapper<NurseHospital> queryWrapper = QueryGenerator.initQueryWrapper(nurseHospital, req.getParameterMap());
            // 使用 eq 防止模糊查询
            Page<NurseHospital> page = new Page<NurseHospital>(pageNo, pageSize);
            SysUser sysuser= sysUserService.getLoginUser();
            queryWrapper.eq("sys_org_code",sysuser.getOrgCode());
            IPage<NurseHospital> pageList = nurseHospitalService.page(page, queryWrapper);
            return Result.OK(pageList);
    }

    /**
     * 【vue3专用】加载节点的子数据
     *
     * @param pid
     * @return
     */
    @RequestMapping(value = "/loadTreeChildren", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeChildren(@RequestParam(name = "pid") String pid) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = nurseHospitalService.queryListByPid(pid);
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】加载一级节点/如果是同步 则所有数据
     *
     * @param async
     * @param pcode
     * @return
     */
    @RequestMapping(value = "/loadTreeRoot", method = RequestMethod.GET)
    public Result<List<SelectTreeModel>> loadTreeRoot(@RequestParam(name = "async") Boolean async, @RequestParam(name = "pcode") String pcode) {
        Result<List<SelectTreeModel>> result = new Result<>();
        try {
            List<SelectTreeModel> ls = nurseHospitalService.queryListByCode(pcode);
            if (!async) {
                loadAllChildren(ls);
            }
            result.setResult(ls);
            result.setSuccess(true);
        } catch (Exception e) {
            e.printStackTrace();
            result.setMessage(e.getMessage());
            result.setSuccess(false);
        }
        return result;
    }

    /**
     * 【vue3专用】递归求子节点 同步加载用到
     *
     * @param ls
     */
    private void loadAllChildren(List<SelectTreeModel> ls) {
        for (SelectTreeModel tsm : ls) {
            List<SelectTreeModel> temp = nurseHospitalService.queryListByPid(tsm.getKey());
            if (temp != null && temp.size() > 0) {
                tsm.setChildren(temp);
                loadAllChildren(temp);
            }
        }
    }

    /**
     * 获取子数据
     *
     * @param nurseHospital
     * @param req
     * @return
     */
    //@AutoLog(value = "护理医院-获取子数据")
    @ApiOperation(value = "护理医院-获取子数据", notes = "护理医院-获取子数据")
    @GetMapping(value = "/childList")
    public Result<IPage<NurseHospital>> queryPageList(NurseHospital nurseHospital, HttpServletRequest req) {
        QueryWrapper<NurseHospital> queryWrapper = QueryGenerator.initQueryWrapper(nurseHospital, req.getParameterMap());
        List<NurseHospital> list = nurseHospitalService.list(queryWrapper);
        IPage<NurseHospital> pageList = new Page<>(1, 10, list.size());
        pageList.setRecords(list);
        return Result.OK(pageList);
    }

    /**
     * 批量查询子节点
     *
     * @param parentIds 父ID（多个采用半角逗号分割）
     * @param parentIds
     * @return
     */
    //@AutoLog(value = "护理医院-批量获取子数据")
    @ApiOperation(value = "护理医院-批量获取子数据", notes = "护理医院-批量获取子数据")
    @GetMapping("/getChildListBatch")
    public Result getChildListBatch(@RequestParam("parentIds") String parentIds) {
        try {
            QueryWrapper<NurseHospital> queryWrapper = new QueryWrapper<>();
            List<String> parentIdList = Arrays.asList(parentIds.split(","));
            queryWrapper.in("pid", parentIdList);
            List<NurseHospital> list = nurseHospitalService.list(queryWrapper);
            IPage<NurseHospital> pageList = new Page<>(1, 10, list.size());
            pageList.setRecords(list);
            return Result.OK(pageList);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return Result.error("批量查询子节点失败：" + e.getMessage());
        }
    }

    /**
     * 添加
     *
     * @param nurseHospital
     * @return
     */
    @AutoLog(value = "护理医院-添加")
    @ApiOperation(value = "护理医院-添加", notes = "护理医院-添加")
    @RequiresPermissions("nurse_hospital:nurse_hospital:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody NurseHospital nurseHospital) {

        nurseHospital.setCode(UUIDGenerator.generate());
        nurseHospitalService.addNurseHospital(nurseHospital);
        return Result.OK("添加成功！");
    }

    /**
     * 编辑
     *
     * @param nurseHospital
     * @return
     */
    @AutoLog(value = "护理医院-编辑")
    @ApiOperation(value = "护理医院-编辑", notes = "护理医院-编辑")
    @RequiresPermissions("nurse_hospital:nurse_hospital:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody NurseHospital nurseHospital) {
        nurseHospitalService.updateNurseHospital(nurseHospital);
        return Result.OK("编辑成功!");
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "护理医院-通过id删除")
    @ApiOperation(value = "护理医院-通过id删除", notes = "护理医院-通过id删除")
    @RequiresPermissions("nurse_hospital:nurse_hospital:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        NurseHospital nurseHospital = nurseHospitalService.getById(id);
        nurseHospitalService.deleteNurseHospital(id);
        // 查询需要克隆的商品
        List<NurseGoods> nurseGoods = nurseGoodsService.list(new QueryWrapper<NurseGoods>().eq("hospital", nurseHospital.getCode()));
        if (!nurseGoods.isEmpty()) {
            nurseGoodsService.removeBatchByIds(nurseGoods);
        }

        // 查询商品详情
        List<NurseGoodsDetail> nurseGoodsDetails = nurseGoodsDetailService.list(new QueryWrapper<NurseGoodsDetail>().exists("SELECT 1 FROM nurse_goods WHERE nurse_goods.id = nurse_goods_detail.id AND hospital = {0}", nurseHospital.getCode()));
        if (!nurseGoodsDetails.isEmpty()) {

        }
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "护理医院-批量删除")
    @ApiOperation(value = "护理医院-批量删除", notes = "护理医院-批量删除")
    @RequiresPermissions("nurse_hospital:nurse_hospital:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        this.nurseHospitalService.removeByIds(Arrays.asList(ids.split(",")));
        return Result.OK("批量删除成功！");
    }

    @AutoLog(value = "护理医院-克隆商品")
    @ApiOperation(value = "护理医院-克隆商品", notes = "护理医院-克隆商品")
    @PostMapping(value = "/clone")
    public Result<?> cloneHospitalGoods(String id, String cloneId) {
        NurseHospital sourceHospital = nurseHospitalService.getById(id);
        NurseHospital targetHospital = nurseHospitalService.getById(cloneId);
        if (sourceHospital == null || targetHospital == null) {
            return Result.error("医院信息为空");
        }
        if (sourceHospital.getId().equals(targetHospital.getId())) {
            return Result.error("不能克隆自身商品");
        }

        // 2. 查询需要克隆的所有商品（包含各级子商品）
        List<NurseGoods> allGoods = nurseGoodsService.list(
                new QueryWrapper<NurseGoods>().eq("hospital", sourceHospital.getCode())
        );
        if (allGoods.isEmpty()) {
            return Result.error("克隆商品为空");
        }

        // 3. 查询所有商品详情
        List<NurseGoodsDetail> allDetails = nurseGoodsDetailService.list(
                new QueryWrapper<NurseGoodsDetail>().exists(
                        "SELECT 1 FROM nurse_goods WHERE nurse_goods.id = nurse_goods_detail.goods_id AND hospital = {0}",
                        sourceHospital.getCode()
                )
        );
        if (allDetails.isEmpty()) {
            return Result.error("商品详情为空");
        }

        // 4. 构建商品详情的映射（原始商品ID→详情列表），方便快速查询
        Map<String, List<NurseGoodsDetail>> goodsIdToDetails = new HashMap<>();
        for (NurseGoodsDetail detail : allDetails) {
            goodsIdToDetails.computeIfAbsent(detail.getGoodsId(), k -> new ArrayList<>())
                    .add(detail);
        }

        // 5. 构建层级关系：父ID→子商品列表（统一父ID为"0"表示顶级，避免null键问题）
        Map<String, List<NurseGoods>> parentIdToChildren = new HashMap<>();
        for (NurseGoods goods : allGoods) {
            String parentId = (goods.getPid() == null || "0".equals(goods.getPid())) ? "0" : goods.getPid();
            parentIdToChildren.computeIfAbsent(parentId, k -> new ArrayList<>())
                    .add(goods);
        }

        // 6. 初始化变量：ID映射表（原始ID→新ID）、待保存的商品和详情列表
        Map<String, String> idMapping = new HashMap<>();
        List<NurseGoods> clonedGoodsList = new ArrayList<>();
        List<NurseGoodsDetail> clonedDetailsList = new ArrayList<>();

        // 7. 按层级处理商品（从顶级开始，逐层处理子商品）
        // 初始待处理的父ID为顶级标识"0"（对应原始商品中pid为null或"0"的商品）
        Queue<String> currentParentIds = new LinkedList<>();
        currentParentIds.add("0");

        while (!currentParentIds.isEmpty()) {
            String parentId = currentParentIds.poll(); // 取出当前层级的父ID（原始ID）
            List<NurseGoods> children = parentIdToChildren.getOrDefault(parentId, Collections.emptyList());

            for (NurseGoods child : children) {
                // 8. 克隆商品并生成新ID
                NurseGoods clonedGoods = new NurseGoods();
                BeanUtils.copyProperties(child, clonedGoods);
                String newGoodsId = IdWorker.getIdStr(clonedGoods); // 生成新ID

                // 设置克隆商品的属性（重置创建/更新信息，关联目标医院）
                clonedGoods.setId(newGoodsId);
                clonedGoods.setCreateBy(null);
                clonedGoods.setCreateTime(null);
                clonedGoods.setUpdateBy(null);
                clonedGoods.setUpdateTime(null);
                clonedGoods.setSysOrgCode(targetHospital.getSysOrgCode());
                clonedGoods.setHospital(targetHospital.getCode());

                // 设置父ID（如果是顶级商品，父ID保持"0"；否则从映射表取父商品的新ID）
                String newParentId = "0".equals(parentId) ? "0" : idMapping.get(parentId);
                if (newParentId == null && !"0".equals(parentId)) {
                    // 校验：非顶级商品必须找到父ID映射（确保层级正确）
                    return Result.error("克隆失败：商品[" + child.getId() + "]的父商品未找到");
                }
                clonedGoods.setPid(newParentId);

                // 9. 记录ID映射，添加到待保存列表
                idMapping.put(child.getId(), newGoodsId);
                clonedGoodsList.add(clonedGoods);

                // 10. 克隆当前商品的详情
                List<NurseGoodsDetail> details = goodsIdToDetails.getOrDefault(child.getId(), Collections.emptyList());
                for (NurseGoodsDetail detail : details) {
                    NurseGoodsDetail clonedDetail = new NurseGoodsDetail();
                    BeanUtils.copyProperties(detail, clonedDetail);
                   // String newDetailId = IdWorker.getIdStr(clonedDetail);

                    clonedDetail.setId(newGoodsId);
                    clonedDetail.setCreateBy(null);
                    clonedDetail.setCreateTime(null);
                    clonedDetail.setUpdateBy(null);
                    clonedDetail.setUpdateTime(null);
                    clonedDetail.setGoodsId(newGoodsId); // 关联克隆后的商品ID

                    clonedDetailsList.add(clonedDetail);
                }

                // 11. 将当前商品的原始ID加入下一层级的父ID队列，准备处理其子女
                currentParentIds.add(child.getId());
            }
        }

        // 12. 批量保存所有克隆的商品和详情
        nurseGoodsService.saveBatch(clonedGoodsList);
        nurseGoodsDetailService.saveBatch(clonedDetailsList);

        return Result.OK("多级服务商品克隆成功！");
    }


    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "护理医院-通过id查询")
    @ApiOperation(value = "护理医院-通过id查询", notes = "护理医院-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<NurseHospital> queryById(@RequestParam(name = "id", required = true) String id) {
        NurseHospital nurseHospital = nurseHospitalService.getById(id);
        if (nurseHospital == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(nurseHospital);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param nurseHospital
     */
    @RequiresPermissions("nurse_hospital:nurse_hospital:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, NurseHospital nurseHospital) {
        return super.exportXls(request, nurseHospital, NurseHospital.class, "护理医院");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    @RequiresPermissions("nurse_hospital:nurse_hospital:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, NurseHospital.class);
    }


    /**
     * URL: /nurse_hospital/nurseHospital/updateUserInfoAfterProfile
     * **/
    @ApiOperation(value = "护工报名审核通过后更新用户数据", notes = "护工报名审核通过后更新用户数据")
    @GetMapping(value = "/updateUserInfoAfterProfile")
    public Result<?> updateUserInfoAfterProfile(
            @RequestParam("hospital")   String hospital_id,
            @RequestParam("idcard")        String idcard,
            @RequestParam("openid")        String openid,
            @RequestParam("name")        String name
    ){
        nurseHospitalService.updateUserInfoAfterProfile(hospital_id, idcard, openid, name);
        return Result.ok(1);
    }
}
